/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.server;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.sss.common.DataReceiver;
import org.sss.common.RoughSizeGetable;
import org.sss.mapreduce.SssException;

/**
 * Cache Data Receiver.
 * 
 * NOTE: thread unsafe.
 */
public class CacheDataReceiver<T extends RoughSizeGetable> implements DataReceiver<T> {
  @SuppressWarnings("unused")
  private static Logger logger = SssServer.getLogger(CacheDataReceiver.class);
  private final List<T> cache;
  private final DataReceiver<List<T>> output;
  private final int limit;
  private int nbytes;

  public CacheDataReceiver(int cacheSize, DataReceiver<List<T>> output) throws SssException {
    this.cache  = new ArrayList<T>(cacheSize);
    this.output = output;
    this.limit  = cacheSize;
  }

  @Override
  public void put(T data) throws SssException {
    cache.add(data);
    nbytes += data.getRoughSize();
    if (nbytes >= limit) {
      flush();
    }
  }

  /**
   * .
   * Note: does not close output.
   */
  @Override
  public void close() throws SssException {
    flush();
  }

  @Override
  public void setError(Throwable e) {
    output.setError(e);
  }

  @Override
  public Throwable getError() {
    return output.getError();
  }

  private void flush() throws SssException {
    output.put(cache);
    cache.clear(); // reuse
    nbytes = 0;
  }
}
